<%--
  Created by IntelliJ IDEA.
  User: jiang
  Date: 2024/12/18
  Time: 8:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
    <title>购物车</title>
    <script src="js/jquery.min.js"></script>
    <script src="js/layer.js"></script>
    <link rel="stylesheet" href="css/cart.css">
    <style>
        .cart-total-hidden {
            display: none;
        }
    </style>
</head>
<body>
<div class="wai">
    <jsp:include page="navigation.jsp"/>

    <div class="cart-container">
        <h2 class="cart-title">我的购物车</h2>
        <!-- 添加全选复选框 -->
        <input type="checkbox" id="selectAll" onclick="selectAllItems(this)">全选
        <c:choose>
            <c:when test="${empty order}">
                <div style="text-align: center; padding: 20px;">
                    购物车还是空的，快去选购商品吧！
                </div>
            </c:when>
            <c:otherwise>
                <c:forEach items="${order.itemMap.values()}" var="item">
                    <div class="cart-item">
                        <!-- 为每个商品添加复选框 -->
                        <input type="checkbox" class="item-checkbox" data-goodsid="${item.goods.id}"
                               onclick="updateTotalPrice()">
                        <img src=".${item.goods.cover}" alt="${item.goods.name}">
                        <div class="item-info">
                            <div class="item-name">${item.goods.name}</div>
                            <div class="item-price">￥${item.price}</div>
                            <div class="item-amount">
                                <button class="amount-btn" onclick="lessen(${item.goods.id})">-</button>
                                <span class="amount-num"> ${item.amount}</span>
                                <button class="amount-btn" onclick="add(${item.goods.id})">+</button>
                                <span class="delete-btn" onclick="deleteItem(${item.goods.id})">删除</span>
                            </div>
                        </div>
                    </div>
                </c:forEach>
                <div class="cart-total cart-total-hidden">
                    总计: <span class="total-price">￥${order.total}</span>
                    <button id="checkoutBtn" class="checkout-button" onclick="goToCheckout()">结算</button>
                </div>
            </c:otherwise>
        </c:choose>
    </div>
</div>
</body>
<script>
    // 全选/取消全选函数
    function selectAllItems(checkbox) {
        var itemCheckboxes = document.querySelectorAll('.item-checkbox');
        var allChecked = true;
        var totalPrice = 0;
        itemCheckboxes.forEach(function (itemCheckbox) {
            itemCheckbox.checked = checkbox.checked;
            if (itemCheckbox.checked) {
                // 计算选中商品的总价
                var price = parseFloat($(itemCheckbox).closest('.cart-item').find('.item-price').text().replace('￥', ''));
                var amount = parseInt($(itemCheckbox).closest('.cart-item').find('.amount-num').text());
                totalPrice += price * amount;
            } else {
                allChecked = false;
            }
        });
        // 更新并显示或隐藏总计价格
        if (allChecked) {
            $('.cart-total').removeClass('cart-total-hidden').find('.total-price').text('￥' + totalPrice.toFixed(2));
        } else {
            $('.cart-total').addClass('cart-total-hidden');
        }
    }

    // 更新总价函数
    function updateTotalPrice() {
        var totalPrice = 0;
        var checkedCheckboxes = document.querySelectorAll('.item-checkbox:checked');
        checkedCheckboxes.forEach(function (checkbox) {
            var price = parseFloat($(checkbox).closest('.cart-item').find('.item-price').text().replace('￥', ''));
            var amount = parseInt($(checkbox).closest('.cart-item').find('.amount-num').text());
            totalPrice += price * amount;
        });
        if (totalPrice > 0) {
            $('.cart-total').removeClass('cart-total-hidden').find('.total-price').text('￥' + totalPrice.toFixed(2));
        } else {
            $('.cart-total').addClass('cart-total-hidden');
        }
    }

    // 加数量
    function add(goodsid) {
        $.ajax({
            url: "goods_buy?goodsid=" + goodsid,
            type: "POST",
            success: function (data) {
                if (data == "ok") {
                    layer.msg("添加成功!");
                    location.reload();
                } else {
                    layer.msg("库存不足!");
                }
            }
        });
    }

    // 减数量
    function lessen(goodsid) {
        $.ajax({
            url: "goods_lessen?goodsid=" + goodsid,
            type: "POST",
            success: function () {
                location.reload();
            }
        });
    }

    // 删除
    function deleteItem(goodsid) {
        $.ajax({
            url: "goods_lessen?goodsid=" + goodsid,
            type: "POST",
            success: function () {
                location.reload();
            }
        });
    }
    function goToCheckout() {
        // 这里可以添加与后端交互确认结算成功的逻辑，比如发送AJAX请求等，目前先简单模拟提示结算成功
        alert("结算成功");

        // 清空购物车中商品展示相关的DOM元素（即每个商品对应的那一组HTML结构）
        var cartItems = document.querySelectorAll('.cart-item');
        cartItems.forEach(function (cartItem) {
            cartItem.remove();
        });

        // 隐藏总计金额显示部分（因为购物车已空）
        $('.cart-total').addClass('cart-total-hidden');

        // 取消全选复选框的选中状态
        document.getElementById('selectAll').checked = false;

        // 可以额外添加提示告知用户购物车已清空
        layer.alert("购物车已清空");
    }
</script>
</html>